package com.example.guardian.home;


import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.example.guardian.R;
import com.example.guardian.myadapter.TCase;
import com.example.guardian.myadapter.T_CaseAdapter;
import com.example.guardian.myadapter.result_adapter;
import com.example.guardian.network.PostKeywords;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import com.speech.setting.IatSettings;
import com.speech.util.JsonParser;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MsgActivity extends AppCompatActivity {
    List<Msg> chatModelList = new ArrayList<Msg>();
    RecyclerView recyclerView;
    MsgAdapter chatAdapter;
    List answer = new ArrayList<String>();

    private static String TAG = MsgActivity.class.getSimpleName();

    ////////////////////////////////////////////////////////////////语音听写对象
    private com.iflytek.cloud.SpeechRecognizer mIat;
    // 语音听写UI
    private RecognizerDialog mIatDialog;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<>();

    private Toast mToast;
    private SharedPreferences mSharedPreferences;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    private String language = "zh_cn";
    private int selectedNum = 0;
    private String[] languageEntries;
    private String[] languageValues;
    private String resultType = "json";

    private StringBuffer buffer = new StringBuffer();


    public static EditText editText;


    private static Object sVmRuntime;
    private static Method setHiddenApiExemptions;

    private ListView listView;

    private List<TCase> tVCaseList = new ArrayList<>();
    private List<ArrayList<String>> kind_list = new ArrayList<ArrayList<String>>();

    private T_CaseAdapter TV_adapter = new T_CaseAdapter(MsgActivity.this,tVCaseList);

    private com.example.guardian.myadapter.result_adapter result_adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        returnanswers("back");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.msg_activity);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.hide();
        }
        Button back_button = findViewById(R.id.qa_back_btn);
        back_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MsgActivity.this.finish();
            }
        });
        initRecycler();
        this.setTitle("小G管家");
        ImageButton beign_speak = (ImageButton) findViewById(R.id.qa_voice);
        Button sendBtn = (Button) findViewById(R.id.send);
        editText = (EditText) findViewById(R.id.input_text);

        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = editText.getText().toString();
                if (!msg.isEmpty()) {
                    Log.d("answer", "begin");
                    returnanswers(msg);
                    sendMessage(msg);
                    editText.setText("");
                } else {
                    Toast.makeText(MsgActivity.this, "请输入信息！", Toast.LENGTH_SHORT).show();
                }
            }
        });


        ///////////////////////////////////////////////////////
        // 初始化识别无UI识别对象
        SpeechUtility.createUtility(MsgActivity.this, SpeechConstant.APPID+ "=8d6a27b7");

        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(MsgActivity.this, mInitListener);

        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(MsgActivity.this, mInitListener);

        mSharedPreferences = getSharedPreferences(IatSettings.PREFER_NAME,
                Activity.MODE_PRIVATE);

        beign_speak.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                ActivityCompat.requestPermissions(MsgActivity.this,
                        new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        1);
                speak();
            }

        });

    }

    private void initRecycler() {
        chatModelList.clear();
        recyclerView = (RecyclerView) findViewById(R.id.msg_recycle_view);
        //给recyclerView创建布局方式
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        //创建适配器
        chatAdapter = new MsgAdapter(chatModelList);
        recyclerView.setAdapter(chatAdapter);
    }

    /**
     * 发送信息
     *
     * @param message
     */
    void sendMessage(String message) {
        Msg chatModel = new Msg(R.drawable.msg1, "我", message, Msg.SEND);
        chatModelList.add(chatModel);
        chatAdapter.notifyItemInserted(chatModelList.size() - 1);
        recyclerView.scrollToPosition(chatModelList.size() - 1);
    }

    /**
     * 接收信息
     *
     * @param message
     */
    void receiveMessage(String message) {
        Msg chatModel = new Msg(R.drawable.msg2, "小G", message, Msg.RECEIVE);
        chatModelList.add(chatModel);
        chatAdapter.notifyItemInserted(chatModelList.size() - 1);
        recyclerView.scrollToPosition(chatModelList.size() - 1);
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////语音
    /**
     * 语音参数设置
     *
     * @return
     */
    public void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);
        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, resultType);

        if (language.equals("zh_cn")) {
            String lag = mSharedPreferences.getString("iat_language_preference",
                    "mandarin");
            // 设置语言
            Log.e(TAG, "language = " + language);
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, lag);
        } else {
            mIat.setParameter(SpeechConstant.LANGUAGE, language);
        }
        Log.e(TAG, "last language:" + mIat.getParameter(SpeechConstant.LANGUAGE));

        //此处用于设置dialog中不显示错误码信息
        //mIat.setParameter("view_tips_plain","false");

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));

        // 设置音频保存路径，保存音频格式支持pcm、wav.
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
                getExternalFilesDir("msc").getAbsolutePath() + "/iat.wav");
    }
    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            Log.d(TAG, "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败，错误码：" + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
            }
        }
    };


    /**
     * 显示结果
     */
    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());
        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }
        editText.setText(resultBuffer.toString());
        editText.setSelection(editText.length());
    }
    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        // 返回结果
        public void onResult(RecognizerResult results, boolean isLast) {
            printResult(results);
        }

        // 识别回调错误
        public void onError(SpeechError error) {
            showTip(error.getPlainDescription(true));
        }

    };
    private void showTip(final String str) {
        if (mToast != null) {
            mToast.cancel();
        }
        mToast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT);
        mToast.show();
    }
    /**
     * 执行在线听写
     */
    private void speak() {
        buffer.setLength(0);
        editText.setText(null);// 清空显示内容
        mIatResults.clear();
        // 设置参数
        setParam();
        mIatDialog.setListener(mRecognizerDialogListener);
        mIatDialog.show();
        showTip(getString(R.string.text_begin));

        // 显示听写对话框
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



    /**
     * 回复
     *
     * @param msg
     */
    void reply(String msg) {
        String rMsg = "";
        switch (msg) {
            case "你好":
                rMsg = "你好 你可以问我一些关于网络诈骗防范的问题哦";
                break;
            case "你是谁":
                rMsg = "我是小G，您的私人反诈顾问";
                break;
            default:
                rMsg = answer.get(0).toString().replace("\"", "").replace(" ", "");
                Log.e("reply", rMsg );

        }
        if (!rMsg.isEmpty()) {
            receiveMessage(rMsg);
        }
    }

    public void returnanswers(String question) {
        answer.clear();
        Log.d("answer", "search");
        PostKeywords.sendOkHttpRequest("http://124.220.154.99:5000/QandA", question, new okhttp3.Callback() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //得到服务器返回的具体内容
                String responsedata = response.body().string();
                showResponse(responsedata);
            }

            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("failure", String.valueOf(e));
                //在这里对异常数据进行处理
            }

            private void showResponse(final String response) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        answer.add(response);
                        reply(question);
                    }
                });
            }
        });
    }

}
